#pragma once
#include "Socket.hpp"
#include "TcpServer.hpp"
#include "Util.hpp"
#include "Log.hpp"
#include <iostream>
#include <string>
#include <memory>
#include <sstream>
#include <unordered_map>

using namespace SocketMoudle;
using namespace LogMoudle;

const std::string gspace = " ";
const std::string glinespace = "\r\n";
const std::string glinesep = ": ";

const std::string webroot = "./wwwroot";
const std::string homepage = "index.html";
const std::string page_404 = "/404.html";
class HttpRequest
{
public:
    HttpRequest()
        : _is_interact(false)
    {
    }
    std::string Serialization()
    {
        return std::string();
    }
    void ParseReqLine(std::string &reqline)
    {
        std::stringstream ss(reqline);
        ss >> _method >> _uri >> _version;
    }
    bool Deserialization(std::string &reqstr)
    {
        // 提取请求行
        std::string reqline;
        bool res = Util::ReadOneLine(reqstr, &reqline, glinespace);
        // 反序列化请求行
        ParseReqLine(reqline);
        if (_uri == "/")
            _uri = webroot + _uri + homepage; // ./wwwroot/index.html
        else
            _uri = webroot + _uri; // ./wwwroot/a/b/c.html
        LOG(loglevel::DEBUG) << "_method: " << _method;
        LOG(loglevel::DEBUG) << "_uri: " << _uri;
        LOG(loglevel::DEBUG) << "_version: " << _version;
        const std::string temp = "?";
        auto pos = _uri.find(temp);
        if (pos == std::string::npos)
        {
            return true;
        }
        _args = _uri.substr(pos + temp.size());
        _uri = _uri.sudstr(0, pos);
        _is_interact = true;
        return true;
    }
    std::string Uri() { return _uri; }
    bool isInteract()
    {
        return _is_interact;
    }
    std::string Args()
    {
        return _args;
    }
    ~HttpRequest()
    {
    }

private:
    std::string _method;
    std::string _uri;
    std::string _version;

    std::unordered_map<std::string, std::string> _headers;
    std::string _blankline;
    std::string _text;

    std::string _args; // 微服务和对应参数
    bool _is_interact; // 是否有动态交互服务
};
class HttpResponce
{
public:
    HttpResponce()
        : _blankline(glinespace), _version("HTTP/1.0")
    {
    }
    std::string Serialization()
    {
        std::string status_line = _version + gspace + std::to_string(_code) + gspace + _desc + glinespace; // 请求行
        std::string resp_header;
        for (auto &e : _headers)
        {
            std::string line = e.first + glinesep + e.second + glinespace;
            resp_header += line;
        }
        return status_line + resp_header + _blankline + _text;
    }
    void SetTargetFile(const std::string &target)
    {
        _targetfile = target;
    }
    void SetCode(int code)
    {
        _code = code;
        switch (_code)
        {
        case 200:
            _desc = "OK";
            break;
        case 404:
            _desc = "Not Found";
            break;
        case 301:
            _desc = "Moved Permanently";
            break;
        case 302:
            _desc = "See Other";
            break;
        default:
            break;
        }
    }
    void SetHeader(const std::string &key, const std::string &value) // 回应报头
    {
        auto iter = _headers.find(key);
        if (iter != _headers.end())
        {
            return;
        }
        _headers.insert(std::make_pair(key, value));
    }
    std::string Uri2Suffix(const std::string &targetfile) // 判断类型资源
    {
        auto pos = targetfile.rfind(".");
        if (pos == std::string::npos)
        {
            return "text/html";
        }
        std::string suffix = targetfile.substr(pos);
        if (suffix == ".html" || suffix == ".htm")
            return "text/html";
        else if (suffix == ".jpg")
            return "image/jpeg";
        else if (suffix == "png")
            return "image/png";
        else
            return "";
    }
    bool MakeResponce()
    {
         if (_targetfile == "./wwwroot/favicon.ico")
        {
            LOG(loglevel::DEBUG) << "用户请求: " << _targetfile << "忽略它";
            return false;
        }
        if (_targetfile == "./wwwroot/redir_test")
        {
            SetCode(301);
            SetHeader("Location", "https://www.qq.com/");//Location负责跳转对应网页
            return true;
        }
        int filesize = 0;
        bool res = Util::ReadFileContent(_targetfile, &_text);
        if (!res)//访问失败
        {
            _text = "";
            SetCode(404);
            _targetfile = webroot + page_404;
            filesize = Util::FileSize(_targetfile);
            Util::ReadFileContent(_targetfile, &_text);
            std::string suffix = Uri2Suffix(_targetfile);//判断类型
             SetHeader("Content-Type", suffix);//资源类型
             SetHeader("Content-Length", std::to_string(filesize));//报文大小
        }
         else
        {
            LOG(loglevel::DEBUG) << "读取文件: " << _targetfile;
            SetCode(200);
            filesize = Util::FileSize(_targetfile);
            std::string suffix = Uri2Suffix(_targetfile);
            SetHeader("Conent-Type", suffix);
            SetHeader("Content-Length", std::to_string(filesize));
            SetHeader("Set-Cookie", "username=zhangsan;");
            // SetHeader("Set-Cookie", "passwd=123456;");
        }
        return true;
    }
     void SetText(const std::string &t)
    {
        _text = t;
    }
    bool Deserialization()
    {
        return true;
    }
    ~HttpResponce()
    {
    }

    // private:
public:
    std::string _version;
    int _code;         // 404
    std::string _desc; // "Not Found"

    std::unordered_map<std::string, std::string> _headers;
    std::vector<std::string> cookie;
    std::string _blankline;
    std::string _text;

    // 其他属性
    std::string _targetfile;
};
using http_func_t = std::function<void(HttpRequest &req, HttpResponce &resp)>;
class Http
{
public:
    Http(uint16_t port)
        : tsvrp(std::make_unique<TcpServer>(port))
    {
    }
    void HandlerHttpRquest(std::shared_ptr<Socket> &sock, InetAddr &client) // 获取请求
    {
        std::string httpreqstr;
        int n = sock->Recv(&httpreqstr);
        if (n > 0)
        {
            HttpRequest req;
            req.Deserialization(httpreqstr);
            // 做出回应
            HttpResponce resp;
            if (req.isInteract())//带有动态服务
            {
                // _uri: ./wwwroot/login
                if (_route.find(req.Uri()) == _route.end())
                {
                    // SetCode(302)
                }
                else
                {
                    _route[req.Uri()](req, resp);//执行动态功能
                    std::string response_str = resp.Serialization();
                    sock->Send(response_str);
                }
            }
            else//只有静态资源
            {
                resp.SetTargetFile(req.Uri());
                if (resp.MakeResponse())
                {
                    std::string response_str = resp.Serialization();
                    sock->Send(response_str);
                }
            }
            // resp.SetTargetFile(req.Uri());
            // resp.MakeResponce();
            // std::string response_str = resp.Serialization();
            // sock->Send(response_str);
        }
    }
    void Start()
    {
        tsvrp->start([this](std::shared_ptr<Socket> &sock, InetAddr &client)
                     { this->HandlerHttpRquest(sock, client); });
    }
     void RegisterService(const std::string name, http_func_t h)
    {
        std::string key = webroot + name; // ./wwwroot/login
        auto iter = _route.find(key);
        if (iter == _route.end())
        {
            _route.insert(std::make_pair(key, h));
        }
    }
    ~Http()
    {
    }

private:
    std::unique_ptr<TcpServer> tsvrp;
    std::unordered_map<std::string, http_func_t> _route;
};